<template>
  <div class="addgoods_container">
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告提示 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
      </el-alert>
      <!-- 步驟條 -->
      <!-- 實現數據聯動：步驟隨著下面 tabs 的切換而切換 -->
      <!-- 共用同一個數據 -->
      <!--TODO: 問題來了：步驟最後一個怎麽切換？ -->
      <el-steps :active="activeIndex - 0" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品參數"></el-step>
        <el-step title="商品屬性"></el-step>
        <el-step title="商品圖片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表單區域 -->
      <el-form :model="addGoodForm" :rules="addGoodFormRules" ref="addGoodFormRef" label-position="top">
        <!-- tabs區域 -->
        <el-tabs v-model="activeIndex" :tab-position="tabPosition" :before-leave="beforeLeave" @tab-click="tabClickEvent">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品價格" prop="goods_price">
              <el-input v-model="addGoodForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品數量" prop="goods_number">
              <el-input v-model="addGoodForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品類別" prop="goods_number">
              <el-cascader v-model="addGoodForm.goods_cat" :options="catesList" expandTrigger="'hover'" :props="props" @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyAttributes" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="item1" v-for="(item1,ind) in item.attr_vals" :key="ind"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyAttributes" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload :on-success="successEvent" :headers="headersObj" :action="pictureURL" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本編輯器 -->
            <quill-editor v-model="addGoodForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="addbtn" @click="addGood">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 圖片預覽對話框 -->
    <el-dialog title="圖片預覽" width="50%" :visible.sync="picDialogVisible">
      <img :src="previewImg" alt="網絡開小差啦！" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'AddGoodsPage',
  data () {
    return {
      activeIndex: '0',
      // 標簽方向
      tabPosition: 'left',
      // 添加商品的整體表單
      addGoodForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        // 圖片上傳的臨時路徑對象
        pics: [],
        // 參數
        attrs: []
      },
      addGoodFormRules: {
        goods_name: [{ required: true, message: '请输入商品名稱', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品價格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品數量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请選擇商品類目', trigger: 'blur' }]
      },
      // 分類數據
      catesList: [],
      props: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 動態參數列表
      manyAttributes: [],
      // 靜態參數列表
      onlyAttributes: [],
      // 上傳圖片路徑
      pictureURL: 'http://175.178.7.145:9988/api/private/v1/upload',
      // 手動設置upload請求頭
      headersObj: { Authorization: window.sessionStorage.getItem('token') },
      // 圖片預覽對話框
      picDialogVisible: false,
      // 預覽路徑
      previewImg: ''
    }
  },
  computed: {
    cateId () {
      if (this.addGoodForm.goods_cat.length === 3) return this.addGoodForm.goods_cat[2]
      return null
    }
  },
  created () {
    this.getCatesData()
  },
  methods: {
    // 獲取分類數據
    async getCatesData () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.message.error('操作失败，请重试！')
      // console.log(res.data)
      this.catesList = res.data
    },
    // 級聯選擇器改變事件
    handleChange () { },
    // 切換標籤頁
    beforeLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodForm.goods_cat.length !== 3) {
        this.$message.error('請選擇商品分類！')
        return false
      }
    },
    // 標籤頁點擊事件
    async tabClickEvent () {
      // 判斷是否進入動態參數頁面
      if (this.activeIndex === '1') {
        // 發送獲取動態參數請求
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) return this.$message.error('操作失败，请重试！')
        // console.log(res.data)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        })
        this.manyAttributes = res.data
        // 判斷是否進入靜態參數頁面
      } else if (this.activeIndex === '2') {
        // 發送獲取動態參數請求
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) return this.$message.error('操作失败，请重试！')
        // console.log(res.data)
        this.onlyAttributes = res.data
      }
    },
    // 處理圖片預覽
    handlePreview (file) {
      console.log(file)
      this.previewImg = file.response.data.url
      this.picDialogVisible = true
    },
    // 處理移除圖片邏輯
    handleRemove (file) {
      console.log(file)
      const filePath = file.response.data.tmp_path
      const ind = this.addGoodForm.pics.findIndex(item => {
        return item.pic === filePath
      })
      this.addGoodForm.pics.splice(ind, 1)
      console.log(this.addGoodForm.pics)
    },
    // 圖片上傳成功之後
    successEvent (response) {
      // console.log(response)
      const picInfo = { pic: response.data.tmp_path }
      this.addGoodForm.pics.push(picInfo)
      // console.log(this.addGoodForm)
    },
    // 添加商品
    addGood () {
      this.$refs.addGoodFormRef.validate(async valid => {
        if (!valid) return this.$message.error('請完整所有必填項！')
        // 發送添加商品請求
        const cloneForm = _.cloneDeep(this.addGoodForm)
        // 分類數據格式化
        cloneForm.goods_cat = cloneForm.goods_cat.join(',')
        // 參數和屬性格式化
        // 數據之間的轉化實在不是很懂
        // 動態參數
        this.manyAttributes.forEach(item => {
          const newAttr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addGoodForm.attrs.push(newAttr)
        })
        // 靜態屬性
        this.onlyAttributes.forEach(item => {
          const newAttr = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodForm.attrs.push(newAttr)
        })
        cloneForm.attrs = this.addGoodForm.attrs
        console.log(cloneForm)
        const { data: res } = await this.$http.post('goods', cloneForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('操作成功！')
        // 商品列表試圖數據的更新
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 25px 0;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.addbtn {
  margin-top: 15px;
}
</style>
